package com.myapp.struts.menu;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;

public class XMLToJava extends MenuRead {

    private ArrayList<FoodItems> foodItemArrayXML = new ArrayList<FoodItems>();

    public ArrayList<FoodItems> readXML(String CountryCode) {
        try {
            URL url = getClass().getResource("dataFiles/InputFiles/FoodItemData.xml");
            File fXmlFile = new File(url.getPath());
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("FoodItem");
            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                    if (eElement.getAttribute("country").equals(Constants.GREAT_BRITAN)) {
                        FoodItems f = new FoodItems();
                        f.setCountry(eElement.getAttribute("country"));
                        f.setCategory(getTagValue("category", eElement));
                        f.setId(getTagValue("id", eElement));
                        f.setDescription(getTagValue("description", eElement));
                        f.setPrice(getTagValue("price", eElement));
                        f.setName(getTagValue("name", eElement));
                        //stores all the food from the XML  file into the Array
                        foodItemArrayXML.add(f);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return foodItemArrayXML;

    }

    public ArrayList<FoodItems> getFoodItemArrayXML() {
        return foodItemArrayXML;
    }

    public void setFoodItemArrayXML(ArrayList<FoodItems> foodItemArrayXML) {
        this.foodItemArrayXML = foodItemArrayXML;
    }

    private static String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

        Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();
    }

    @Override
    public ArrayList<FoodItems> ReadMenu(String CountryCode) {

        return readXML(CountryCode);
    }
}